"""
线程共享全局变量，一起写会有资源竞争问题
使用互斥锁进行同步控制
"""
import threading
import time

g_num = 0


def test1(count):
    global g_num
    # 上锁
    mutex.acquire()
    for i in range(count):
        g_num += 1

    # 释放锁
    mutex.release()
    print("test2 count = %d" % g_num)


def test2(count):
    global g_num
    mutex.acquire()
    for i in range(count):
        g_num += 1
    mutex.release()
    print("test2 count = %d" % g_num)


def main():
    t1 = threading.Thread(target=test1, args=(10000000,))
    t2 = threading.Thread(target=test2, args=(10000000,))
    t1.start()
    t2.start()
    time.sleep(2)
    print("main count = %d" % g_num)


# 实例化互斥锁，默认没有上锁
mutex = threading.Lock()

if __name__ == '__main__':
    main()
